<#import "../common/layout.ftl" as layout/>
<#import "../common/dataTables.ftl" as dataTables/>
<#import "../common/modern-forms.ftl" as mform/>
<#import "../common/modal.ftl" as modal/>

<!DOCTYPE html>
<html>
<@layout.head title="用户管理">
    <@dataTables.head/>
    <@dataTables.buttons_head/>
    <@dataTables.select_head/>
    <@dataTables.fixedHeader_head/>
    <@mform.head/>
</@layout.head>
<body>
<@layout.page>
<div class="main-box">
<#--<h4 class="page-header">-->
<#--<i class="fa fa-cog fa-spin"></i>-->
<#--用户管理-->
<#--</h4>-->

    <!-- 表格 -->
    <div class="content">
        <!-- 按钮 -->
        <div id="mUserBtnGroup" class="btn-group" style="position: absolute;top:0;">
            <button type="button" class="btn btn-blue btn-sm"
                    onclick="javascript:refreshData();">
                <i class="fa fa-refresh"></i> 刷新
            </button>
            <button id="btnAddTopMenu" type="button" class="btn btn-blue btn-sm" style="margin-left: 5px;"
                    onclick="javascript:newmUser();">
                <i class="fa fa-plus"></i> 新增
            </button>
            <button id="btnAddTopMenu" type="button" class="btn btn-blue btn-sm" style="margin-left: 5px;"
                    onclick="javascript:editmUser();">
                <i class="fa fa-edit"></i> 修改
            </button>
            <button id="btnAddTopMenu" type="button" class="btn btn-blue btn-sm" style="margin-left: 5px;"
                    onclick="javascript:delmUser();">
                <i class="fa fa-minus"></i> 删除
            </button>

        </div>
        <!-- 表格 -->
        <@dataTables.commonTable id="tabmUser"/>

        <!-- 弹出窗 -->
        <@modal.editModal id="modal-mUser" buttonId="btnmUserSave" width="500px">
            <@mform.container id="userEditForm">
                <input id="cUserID" name="cUserID" type="hidden"/>
                <@mform.row>
                    <@mform.input_text id="cUserCode" name="cUserCode" size=6
                    label="用户编码" placeholder="请输入用户编码" icon="fa-edit" />
                    <@mform.input_text id="cUserName" name="cUserName" size=6
                    label="用户名" placeholder="请输入用户名" icon="fa-edit" />
                <#--<@mform.select2 id="cGender" name="cGender" label="性别"  size=6>-->
                <#--<option value="-1">请选择</option>-->
                <#--<option value="未知" selected="true">未知</option>-->
                <#--<option value="男">男</option>-->
                <#--<option value="女">女</option>-->
                <#--</@mform.select2>-->
                    <@mform.input_password id="cPassword" name="cPassword"  size=6
                    label="密码" placeholder="请输入账户密码" icon="fa-edit"/>

                    <@mform.select2 id="bState" name="bState" label="账户状态"  size=6>
                        <option value="-1">请选择</option>
                        <option value="1" selected="true">启用</option>
                        <option value="0">停用</option>
                    </@mform.select2>
                    <@mform.input_textarea id="cDescribe" name="cDescribe" size=12 label="描述" placeholder="请输入描述"/>

                </@mform.row>
            </@mform.container>
        </@modal.editModal>

        <@modal.editModal id="userASrole" buttonId="saveAssociation" width="500px">
            <@mform.container id="userrolecon">
                <@mform.row>
                    <input id="userID" name="userID" type="hidden"/>
                    <input id="userName" name="userName" type="hidden"/>
                </@mform.row>
            </@mform.container>
            <@dataTables.commonTable id="tabUserasRole"/>
        </@modal.editModal>

    </div>
</div>
</@layout.page>
<@layout.foot>
    <@dataTables.foot/>
    <@dataTables.buttons_foot/>
    <@dataTables.select_foot/>
    <@dataTables.fixedHeader_foot/>
    <@mform.foot/>

<script type="text/javascript">
    var columns =
            [

                {"title": "用户ID", "data": "cUserID"},
                {"title": "用户编码", "data": "cUserCode"},
                {"title": "用户名", "data": "cUserName"},
//                {"title": "性别", "data": "cGender", "sWidth": "14%"},
                 {"title": "状态", "data": "bState"},
        {
            "title": "操作",
            "data": null,
            "sWidth": "17%",
            "className": "center btn-table",
            "defaultContent": "<button type=\"button\" id=\"asroles\" class=\"btn btn-link btn-table-icon\"  title=\"设置用户对应的角色\"><i class='fa fa-exchange' style='color:#336600'></i></button> <button type=\"button\" id=\"resetpassword\" class=\"btn btn-link btn-table-icon\"  title=\"重置密码\"><i class='fa fa-lock' style='color:Black'></i></button>"
        }
    ];

    var mUserTable = $('#tabmUser').winningTable({
        columns: columns,
        pageLength: 10,
        // toolbar: "#mUserBtnGroup",
        /*select: {style: 'multi'},*/
        fixedHeader: false,
        searching: true,
        ordering: true,
        "columnDefs": [{
            "targets": [0],
            "visible": false
        }],
        buttons: [

        ],
        "rowCallback": function (row, data, index) {
            if (data.bState == true) {
                $('td:eq(2)', row).html('启用');
            } else {
                $('td:eq(2)', row).html('停用');
            }

            if (data.bState == false) {
                $('td', row).css('color', '#ff483f');
            }
        }
    });

    var uAr_columns =
            [
                {
                    "title": "active",
                    "data": null,
                    "className": "center",
                    "defaultContent": "<input type=\"checkbox\" id=\"selectAction\" class=\"editor-active\"/>"
                },
                {"title": "角色编码", "data": "cRoleID"},
                {"title": "角色名称", "data": "cRoleName"}
            ];
    var uAr_table = $('#tabUserasRole').winningTable({
        retrieve: true,
        columns: uAr_columns,
        paging: false,
        fixedHeader: false,
        buttons: [],
        select: {style: 'multi'},
        "columnDefs": [{
            "targets": [0, 1],
            "visible": false
        }],
        "createdRow": function (row, data, dataIndex) {
            if (data.active == '1') {
                uAr_table.dataTables.row(dataIndex).select();
            }
        }
    });

    $('#tabmUser').on("click", "#resetpassword", function () {
        var item = mUserTable.dataTables.row($(this).closest('tr')).data();
        swal({
            title: "确定重置密码",
            text: "是否确定将改用户密码重置为\"123456\"",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "是的,确定",
            cancelButtonText: "取消"
        }).then(function (result) {
            if(result.value)
            {
                $.ajax({
                    type: 'POST',
                    data: 'cUserCode=' + item.cUserCode,
                    url: '${request.contextPath}/usermanage/resetpassword',
                    success: function (data) {
                        //成功之后
                        if (data.success) {
                            swal({
                                title: "成功",
                                text: "操作成功!",
                                type: "success",
                                showCancelButton: false,
                                confirmButtonText: "确定"
                            });
                        }
                        else {
                            swal("错误", data.errorMsg, "error");
                        }
                    },
                    error: function (xhr, type) {
                        swal("错误", "系统发生内部错误!请稍后再试!", "error");
                    }
                });
            }
        });
    });

    $('#tabUserasRole').on("click", "#selectAction", function () {
        uAr_table.dataTables.row($(this).closest('tr')).select();
    });

    $('#tabmUser').on("click", "#asroles", function () {
        var item = mUserTable.dataTables.row($(this).closest('tr')).data();
        getRoles(item);
    });

    mUserTable.queryData("usermanage/queryAll");

    function newmUser() {
        $('#modal-mUser').find(".modal-title").text('新增用户信息');
        clearForm($('#modal-mUser'));
        $("#cPassword").parent().parent().attr("style", "display:block");
        $("#cPassword").val('123456');
        $("#btnmUserSave").unbind();
        $("#btnmUserSave").click(savemUserNew);
        $('#modal-mUser').modal();
    }

    function editmUser() {
        var datas = mUserTable.getSelectedDatas();
        if (datas == null || datas.length == 0 || datas.length > 1) {
            swal("错误", "请选择一行数据", "error");
            return;
        }
        var $modal = $("#modal-mUser");
        $modal.find(".modal-title").text("修改用户信息");
        clearForm($modal);
        var data = datas[0];

        if (data.bState == true) {
            data.bState = "1";
        } else {
            data.bState = "0";
        }

        initFormItemData($("#userEditForm"), data);
        $("#cPassword").parent().parent().attr("style", "display:none");
        $("#btnmUserSave").unbind();
        $("#btnmUserSave").click(savemUserUpdate);
        $modal.modal();
        $modal.on('shown.bs.modal', function (e) {
//            initFormSelect($("#modal-mUser"), data);
        })
    }

    function refreshData() {
        mUserTable.queryData("usermanage/queryAll");
    }

    function delmUser() {
        var datas = mUserTable.getSelectedDatas();
        if (datas == null || datas.length == 0 || datas.length > 1) {
            swal("错误", "请选择一行数据", "error");
            return;
        }
        var data = datas[0];
        var cUserID = data.cUserID;
        swal({
            title: "确定删除",
            text: "是否确定删除此数据",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "是的,确定",
            cancelButtonText: "取消"
        }).then(function (result) {
            if(!result.value)
                return;
            $.ajax({
                type: 'POST',
                data: 'cUserID=' + cUserID,
                url: '${request.contextPath}/usermanage/delete',
                success: function (data) {
                    //成功之后
                    if (data.success) {
                        swal({
                            title: "成功",
                            text: "操作成功!",
                            type: "success",
                            showCancelButton: false,
                            confirmButtonText: "确定"
                        }).then(function (result) {
                            var newRow = data.data;
                            // 删除table行
                            mUserTable.getSelectedRows().remove().draw();
                        });
                    }
                    else {
                        swal("错误", data.errorMsg, "error");
                    }
                },
                error: function (xhr, type) {
                    swal("错误", "系统发生内部错误!请稍后再试!", "error");
                }
            });
        });
    }

    function savemUserNew() {
        $("#cDeptName").val($("#cDeptID").find("option:selected").text());
        $("#cPlaceName").val($("#cPlaceID").find("option:selected").text());
        var pass = validateItemNotNull($("#cUserCode"));
        pass = pass && validateItemNotNull($("#cUserName"));
        pass = pass && validateItemNotNull($("#cPassword"));
        if (!pass) {
            return;
        }
        if ($("#bState").val() == '-1') {
            swal("提示", "请选择用户状态", "warning");
            return;
        }
        swal({
            title: "确定新增",
            text: "是否确定新增此数据",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "是的,确定",
            cancelButtonText: "取消"
        }).then(function (result) {
            if(!result.value)
                return;
            var requestData = $("#userEditForm form").serialize();
            $.ajax({
                type: 'POST',
                data: requestData,
                url: '${request.contextPath}/usermanage/new',
                success: function (data) {
                    //成功之后
                    if (data.success) {
                        swal({
                                    title: "成功",
                                    text: "操作成功!",
                                    type: "success",
                                    showCancelButton: false,
                                    confirmButtonText: "确定"
                                }).then(function (result) {
                                    var newRow = data.data;
//                                    if (newRow.bState == '1')
//                                        newRow.bState = '启用';
//                                    else newRow.bState = '停用';
                                    var row = mUserTable.dataTables.row.add(newRow).draw().node();
                                    $(row).insertBefore(mUserTable.dataTables.rows().nodes()[0]);
                                    $("#modal-mUser").modal('hide');
                                });
                    }
                    else {
                        swal("错误", data.errorMsg, "error");
                    }
                },
                error: function (xhr, type) {
                    swal("错误", "系统发生内部错误!请稍后再试!", "error");
                }
            });
        });
    }

    function savemUserUpdate() {
        var pass = validateItemNotNull($("#cUserCode"));
        pass = pass && validateItemNotNull($("#cUserName"));
        if (!pass) {
            return;
        }
        if ($("#bState").val() == '-1') {
            swal("提示", "请选择用户状态", "warning");
            return;
        }
//        if ($("#cGender").val() == '-1') {
//            swal("提示", "请选择性别", "warning");
//            return;
//        }

        swal({
            title: "确定修改",
            text: "是否确定修改此数据",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "是的,确定",
            cancelButtonText: "取消"
        }).then(function (result) {
            if (result.value) {
                var requestData = $("#userEditForm form").serialize();
                $.ajax({
                    type: 'POST',
                    data: requestData,
                    url: '${request.contextPath}/usermanage/edit',
                    success: function (data) {
                        //成功之后
                        if (data.success) {
                            swal({
                                title: "成功",
                                text: "操作成功!",
                                type: "success",
                                showCancelButton: false,
                                confirmButtonText: "确定"
                            }).then(function (result) {
                                var newRow = data.data;
                                if (newRow.bState == '1')
                                    newRow.bState = '启用';
                                else newRow.bState = '停用';
                                var index = mUserTable.getSelectedRows()[0];
                                mUserTable.dataTables.row(index).data(newRow);
                                $("#modal-mUser").modal('hide');

                            });


                        }
                        else {
                            swal("错误", data.errorMsg, "error");
                        }
                    },
                    error: function (xhr, type) {
                        swal("错误", "系统发生内部错误!请稍后再试!", "error");
                    }
                });
            }
        });

//        swal({
//            title: "确定修改",
//            text: "是否确定修改此数据",
//            type: "warning",
//            showCancelButton: true,
//            confirmButtonColor: "#DD6B55",
//            confirmButtonText: "是的,确定",
//            cancelButtonText: "取消"
//        }, function () {
//
//        });
    }

    function getRoles(item) {
        clearForm($("#userASrole"));
        var $modal = $("#userASrole");
        $modal.find(".modal-title").text("用户角色关联");
        var cUserID = item.cUserID;
        var cUserName = item.cUserName;
        $("#userID").val(cUserID);
        $("#userName").val(cUserName);
        $("#saveAssociation").unbind();
        $("#saveAssociation").click(saveAssociation);
        $modal.modal();

        var param = {};
        param.cUserID = $("#userID").val();
        uAr_table.queryData("${request.contextPath}/usermanage/queryURassociation", param);
    }

    function saveAssociation() {

        var params = {datas: "{\"cUserID\":\"" + $("#userID").val() + "\",\"selected\":" + JSON.stringify(uAr_table.getSelectedDatas().toArray()) + "}"};
        $.ajax({
            type: 'POST',
            data: params,
            url: '${request.contextPath}/usermanage/save',
            success: function (data) {
                if (data.success) {
                    $.bootstrapGrowl("操作成功", {
                        type: 'success',
                        offset: {from: 'top', amount: 0},
                        align: 'center',
                        width: 'auto',
                        delay: 6000
                    });
                    $("#userASrole").modal('hide');
                }
                else {
                    swal("错误", data.errorMsg, "error");
                }
            },
            error: function (xhr, type) {
                swal("错误", "系统发生内部错误!请稍后再试!", "error");
            }
        });
    }
</script>
</@layout.foot>
</body>
</html>